<template>
  <div class="pc-role-bg">
    <RemindWebSocket />
    <div class="layout-container">
      <!-- 侧边栏 -->
      <SideBar />
      <!-- 主内容区 -->
      <div class="main-content main-content-rounded" style="display: flex; flex-direction: column">
        <div class="role-title-row main-header">
          <el-icon class="back-btn" @click="goBack">
            <ArrowLeft />
          </el-icon>
          <span class="role-title">修改角色信息</span>
        </div>
        <div class="main-divider"></div>
        <!-- 角色卡片区 -->
        <div class="role-card-list">
          <!-- 加载/空态提示 -->
          <div v-if="relativeLoading" class="loading-tip">加载中…</div>
          <div v-else-if="roles.length === 0 && !isMobile" class="empty-tip">暂无角色，点击下方“新增角色”进行添加</div>
          <el-row v-if="!relativeLoading" :gutter="24">
            <el-col v-for="role in roles" :key="role.relativeId" :span="6">
              <el-card class="role-info-card">
                <div class="role-info-content-wrap">
                  <div class="role-info-content">
                    <div class="role-info-avatar">
                      <el-avatar :size="70" :src="getRoleAvatar(role)" />
                    </div>
                    <div class="role-info-main">
                      <div class="role-info-name">{{ role.name }}</div>
                      <div class="role-info-relation">
                        {{ role.relationship || "-" }}
                      </div>
                    </div>
                  </div>
                  <div class="role-info-age">
                    {{ role.age }}<span class="role-info-age-unit">岁</span>
                  </div>
                </div>
                <div class="role-info-actions">
                  <el-button class="role-info-action-btn" link type="primary" @click="onEditRole(role)"><el-icon
                      style="vertical-align: middle; margin-right: 4px">
                      <EditPen />
                    </el-icon>修改</el-button>
                  <div class="role-info-action-divider"></div>
                  <el-button class="role-info-action-btn delete" link type="danger" @click="onDeleteRole(role)"><el-icon
                      style="vertical-align: middle; margin-right: 4px">
                      <DeleteFilled />
                    </el-icon>删除</el-button>
                </div>
              </el-card>
            </el-col>
            <!-- 新增卡片 -->
            <el-col v-if="roles.length === 0 && isMobile">
              <div class="empty-tip">暂无角色，点击下方“新增角色”进行添加</div>
            </el-col>
            <el-col :span="6">
              <el-card class="role-info-card" @click="onAddRole">
                <div class="role-info-add">
                  <el-icon class="role-info-add-icon">
                    <Plus />
                  </el-icon>
                  <div class="role-info-add-text">新增角色</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { go } from "@/utils/nav.js";
import {
  ArrowLeft,
  Plus,
  EditPen,
  DeleteFilled,
} from "@element-plus/icons-vue";
import SideBar from "/pages/pc/sideBar.vue";
import { useUserStore } from "@/store/modules/user";
import { useRelativeStore } from "@/store/modules/relative";
import { deleteRelative } from "@/api/pc/elderly";
import { ElMessageBox } from "element-plus";
import RemindWebSocket from "@/components/RemindWebSocket.vue";
const userStore = useUserStore();
const relativeStore = useRelativeStore();
const roles = computed(() => relativeStore.processedList || []);
const relativeLoading = computed(() => relativeStore.loading);
// 获取屏幕宽度
const screenWidth = ref(window.innerWidth)
console.log("screen", screenWidth.value)
// 是否是手机尺寸
const isMobile = computed(() =>
  screenWidth.value < 768
)
console.log("isMobile", isMobile.value)
const goBack = () => {
  go("/pages/pc/index");
};
const onEditRole = (role) => {
  if (!role) return;
  // 修正：API返回的是 relativeId，不是 id
  const rid = role.relativeId;
  if (!rid) {
    uni.showToast({ title: '当前数据缺少ID，无法编辑', icon: 'none' });
    return;
  }
  relativeStore.setCurrentRelativeId(rid);
  try {
    go("/pages/pc/role-create?relativeId=" + rid);
  } catch (e) {
    go("/pages/pc/role-create?relativeId=" + rid);
  }
};
const onDeleteRole = async (role) => {
  if (!role || !role.relativeId) {
	uni.showToast({ title: '当前数据缺少ID，无法删除', icon: 'none' });
    return;
  }

  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      `确定要删除角色"${role.name}"吗？删除后无法恢复。`,
      "确认删除",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "el-button--danger",
      }
    );

    // 调用删除接口
    const response = await deleteRelative(role.relativeId);

    if (response.code === 200) {
      uni.showToast({ title: '角色删除成功', icon: 'success' });
      // 清除当前角色相关的缓存数据
      relativeStore.setCurrentRelativeId(null);
      
      // 从所有缓存中移除已删除的角色
      relativeStore.removeRelativeFromCache(role.relativeId);
      // 刷新角色列表
      await relativeStore.fetchList(userStore.id);
      // 同时刷新首页列表，确保数据一致性
      await relativeStore.fetchHomeList(userStore.id);
      
      // 检查是否还有角色，如果没有则跳转到首页
      if (!relativeStore.list || relativeStore.list.length === 0) {
		uni.showToast({ title: '所有角色已删除，即将返回首页', icon: 'none' });
        setTimeout(() => {
          go('/pages/pc/index', { replace: true });
        }, 1500);
      }
    } else {
	  uni.showToast({ title: response.msg || "删除失败", icon: 'none' });
    }
  } catch (error) {
    if (error === "cancel") {
      // 用户取消删除
      return;
    }
    console.error("删除角色失败:", error);
	uni.showToast({ title: '删除失败，请重试', icon: 'none' });
  }
};
const onAddRole = () => {
  go("/pages/pc/role-create?mode=create&from=role-edit");
};

// 获取角色头像（优先使用预计算的 avatarUrl，其次使用文件base64）
const getRoleAvatar = (role) => {
  if (role && role.avatarUrl) {
    return role.avatarUrl;
  }
  if (
    role.personalityProfile &&
    Array.isArray(role.personalityProfile) &&
    role.personalityProfile.length > 0
  ) {
    const firstProfile = role.personalityProfile[0];
    if (firstProfile.fileBase64) {
      // 检查是否已经是完整的Data URL
      if (firstProfile.fileBase64.startsWith("data:")) {
        return firstProfile.fileBase64;
      } else {
        // 构建完整的Data URL
        const mimeType = firstProfile.mimeType || "image/png";
        return `data:${mimeType};base64,${firstProfile.fileBase64}`;
      }
    }
  }
  // 如果没有头像数据，根据性别返回不同的默认头像
  const gender = role?.gender;
  if (gender === '女') {
    return '/static/images/p2.png';
  }
  // 默认使用男性头像（包括男或者其他未知性别）
  return "/static/images/p1.png";
};

// 添加一个新的响应式变量来跟踪刷新状态
const refreshKey = ref(0);

// // 添加一个强制刷新函数
// const forceRefresh = async () => {
//   refreshKey.value++;
//   if (!userStore.id) {
//     go('/pages/pc/login', { replace: true });
//     return;
//   }
//   // 强制刷新数据
//   try {
//     await Promise.all([
//       relativeStore.fetchHomeList(userStore.id),
//       relativeStore.fetchList(userStore.id)
//     ]);
//   } catch (error) {
//     console.error('获取角色列表失败:', error);
//   }
// };

// onActivated(async () => {
//   // 当页面被激活时强制刷新数据
//   await forceRefresh();
// });

onMounted(async () => {
  if (!userStore.id) {
    go("/pages/pc/login", { replace: true });
    return;
  }
  // 进入页面时加载基础列表并异步刷新完整数据以更新头像缓存
  await forceRefresh();
  
  // 如果没有角色可编辑，则跳转到首页
  if (!relativeStore.list || relativeStore.list.length === 0) {
	uni.showToast({ title: '暂无角色可编辑', icon: 'none' });
    go('/pages/pc/index', { replace: true });
  }
});
</script>

<style scoped>
.layout-container {
  display: flex;
  min-height: 100vh;
  background-color: #1976ed;
  border-radius: 0;
  overflow: hidden;
  position: relative;
}

.main-content.main-content-rounded {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 24px 0 0 24px;
  padding-top: 20px;
  overflow-y: auto;
}

.role-title-row {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.main-header {
  height: 64px;
  display: flex;
  align-items: center;
  padding-left: 24px;
  background: #fff;
  font-size: 20px;
  font-weight: 600;
  border-bottom: none;
}

.back-btn {
  font-size: 32px;
  color: #222;
  cursor: pointer;
  margin-right: 18px;
  font-weight: 700;
}

.role-title {
  font-size: 32px;
  font-weight: 700;
  color: #222;
}

.main-divider {
  height: 1px;
  background: #e3e7ed;
  margin: 0 -32px 0 -32px;
}

.role-card-list {
  background: #f7f8fa;
  padding: 32px 20px 0 32px;
  min-height: 400px;
  display: flex;
  align-content: flex-start;
  gap: 32px 32px;
  flex: 1;
  min-height: 0;
}

.el-row {
  flex-wrap: wrap !important;
  align-content: flex-start;
}

.el-col {
  flex: 0 0 25%;
  max-width: 25%;
  box-sizing: border-box;
  display: flex;
}

@media (max-width: 1200px) {
  .el-col {
    flex: 0 0 33.3333%;
    max-width: 33.3333%;
  }
}

@media (max-width: 900px) {
  .el-col {
    flex: 0 0 50%;
    max-width: 50%;
  }
}

@media (max-width: 600px) {
  .el-col {
    flex: 0 0 100%;
    max-width: 100%;
  }
}

.role-info-card {
  width: 700px;
  height: 160px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 16px #e3e7ed;
  display: flex;
  flex-direction: column;
  padding: 20px 0 10px 0;
  position: relative;
  margin-bottom: 20px;
}

.role-info-content {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
  margin-bottom: 12px;
  position: relative;
}

.role-info-avatar {
  margin-right: 12px;
  flex-shrink: 0;
}

.role-info-main {
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-width: 0;
  z-index: 2;
}

.role-info-name {
  font-size: 20px;
  font-weight: 700;
  color: #222;
  margin-bottom: 4px;
  word-break: keep-all;
  background: #fff;
  padding-right: 8px;
  position: relative;
}

.role-info-relation {
  font-size: 14px;
  color: #888;
  word-break: keep-all;
  background: #fff;
  padding-right: 8px;
  position: relative;
}

.role-info-age {
  font-size: 30px;
  font-weight: 700;
  color: #2f3a50;
  position: absolute;
  right: 12px;
  top: 6px;
  transform: none;
  white-space: nowrap;
  line-height: 1;
  background: #fff;
  padding: 0 4px;
  border-radius: 6px;
  z-index: 3;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.03);
}

.role-info-age-unit {
  font-size: 14px;
  margin-left: 2px;
  opacity: 0.85;
}

.role-info-content-wrap {
  position: relative;
  width: 100%;
  min-height: 72px;
  display: flex;
  align-items: center;
  flex: 1;
}

.role-info-actions {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 0;
  border-top: 1px solid #e3e7ed;
  padding-top: 10px;
  margin-top: 15px;
}

.role-info-avatar {
  margin-top: -8px;
}

.role-info-name {
  margin-bottom: 4px;
}

.role-info-action-btn {
  flex: 1;
  text-align: center;
  border: none;
  background: none;
  font-size: 16px;
  color: #1976ed;
  padding: 0;
}

.role-info-action-btn.delete {
  color: #ff3b30;
}

.role-info-action-divider {
  width: 1px;
  height: 35px;
  background: #e3e7ed;
  margin: 0 12px;
}

.role-info-add-card {
  border: 1px solid #e3e7ed;
  background: #fff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 16px;
  box-shadow: 0 2px 16px #e3e7ed;
  width: 401px;
  height: 160px;
  flex-direction: column;
  padding: 24px 0 8px 0;
  margin-bottom: 8px;
}

.role-info-add {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.role-info-add-icon {
  font-size: 32px;
  color: #222;
  margin-bottom: 8px;
}

.role-info-add-text {
  font-size: 18px;
  color: #888;
  margin-top: 12px;
}

.loading-tip {
  color: #888;
  font-size: 14px;
  margin: 0 0 16px 8px;
}

.empty-tip {
  color: #888;
  font-size: 14px;
  margin: 0 0 16px 8px;
}

@media (max-width: 1200px) {
  .role-info-age {
    right: 0;
    font-size: 22px;
  }

  .role-info-content-wrap {
    min-height: 56px;
  }
}

@media (max-width: 900px) {
  .role-info-content {
    align-items: flex-start;
    min-height: unset;
  }

  .role-info-age {
    position: static;
    margin-left: 0;
    font-size: 18px;
    display: block;
    background: none;
    padding: 0;
    border-radius: 0;
  }

  .role-info-content-wrap {
    align-items: flex-start;
    min-height: unset;
  }
}

@media screen and (max-width: 768px) {
  .role-info-card {
    border: 1px solid #e3e7ed;
    background: #fff;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 16px;
    box-shadow: 0 2px 16px #e3e7ed;
    width: 70vw;
    height: 160px;
    flex-direction: column;
    padding: 24px 0 8px 0;
    margin-bottom: 8px;
  }

  .empty-tip-mobile {
    display: block;
    color: #888;
    font-size: 14px;
    /* margin: 0 0 16px 8px; */
    width: 100%;
    padding: 20px;
    /* text-align: center; */
  }

  .role-card-list {
    background: #f7f8fa;
    padding: 32px 20px 0 32px;
    min-height: 400px;
    display: flex;
    align-content: flex-start;
    gap: 32px 32px;
    overflow: scroll;
    height: 80vh;
    flex: none;
  }

  .role-info-card {
    width: 70vw;
    height: 160px;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 16px #e3e7ed;
    display: flex;
    flex-direction: column;
    padding: 20px 0 10px 0;
    position: relative;
    margin-bottom: 20px;
  }
}

@media screen and (min-width:768px) and (max-width:1024) {
  .empty-tip {
    display: none;
  }
}
</style>
